package com.lanp.springmongodb.controller;

import com.lanp.springmongodb.dao.m1.Comment1Dao;
import com.lanp.springmongodb.dao.m2.Comment2Dao;
import com.lanp.springmongodb.model.Comment;
import com.lanp.springmongodb.service.Cs;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("test")
public class TestRest {

    @Autowired
    private Cs cs;

    @Autowired
    private Comment1Dao commentDaoM1;
    @Autowired
    private Comment2Dao commentDaoM2;
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 保存一个评论
     */
    @RequestMapping("testSaveComment")
    public void testSaveComment() {
        Comment comment = new Comment();
        comment.setArticleid("100000");
        comment.setContent("测试添加的数据");
        comment.setCreatedatetime(LocalDateTime.now());
        comment.setUserid("1003");
        comment.setNickname("凯撒大帝");
        comment.setState("1");
        comment.setLikenum(0);
        comment.setReplynum(0);
        cs.saveComment(comment);
    }

    @RequestMapping("query")
    public Object query(){
        BasicDBObject basicDBObject = new BasicDBObject("userid", 1);


        BasicDBList basicDBList = new BasicDBList();
        BasicDBObject basicDBObject1 = new BasicDBObject();
        basicDBObject1.put("state","2");
        basicDBObject1.put("likenum","1");
        basicDBList.add(basicDBObject1);
        BasicDBObject and = new BasicDBObject("$and",basicDBList);



        BasicDBList queryList = new BasicDBList();
        queryList.add(basicDBObject);
        queryList.add(and);

        BasicDBObject andDBObject = new BasicDBObject("$and", queryList);


        List<Comment> comments = mongoTemplate.find(new BasicQuery(andDBObject.toJson()), Comment.class);
        return comments;
    }

    /**
     * 查询所有数据
     */
    @RequestMapping("testFindAll")
    public Object testFindAll() {
        Map<String, Object> res = new HashMap<>();
        List<Comment> list = cs.findCommentList();
        System.out.println(list);
        res.put("default", list);

        List<Comment> all = commentDaoM1.findAll();
        res.put("m1", all);

        List<Comment> all2 = commentDaoM2.findAll();
        res.put("m2", all2);
        return res;
    }

    /**
     * 测试根据id查询
     */
    @RequestMapping("testFindCommentById")
    public Comment testFindCommentById(String id) {
        Comment comment = cs.findCommentById(id);
        System.out.println(comment);
        return comment;
    }
}
